﻿using System.Collections.Generic;
using System.Reflection;
using System.Xml.Linq;

namespace Dapper.Sharding
{
    internal class DbCsharpTypeMap
    {
        private static readonly Dictionary<string, List<DbCsharpTypeEntity>> Dict = new();

        static DbCsharpTypeMap()
        {
            using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Dapper.Sharding.DbTypeMap.xml");
            XDocument doc = XDocument.Load(stream);
            XElement DbTypeMapElement = doc.Element("DbTypeMap");

            foreach (XElement element in DbTypeMapElement.Elements("Database")) //遍历数据库
            {
                string dbProvider = element.Attribute("DbProvider").Value;
                string language = element.Attribute("Language").Value;
                string key = dbProvider + language;

                if (!Dict.ContainsKey(key))
                {
                    var list = new List<DbCsharpTypeEntity>();
                    foreach (XElement el in element.Elements("DbType")) //遍历语言转换
                    {
                        string Name = el.Attribute("Name").Value;
                        string To = el.Attribute("To").Value.Replace("&lt;", "<").Replace("&gt;", ">");
                        DbCsharpTypeEntity model = new()
                        {
                            DbType = Name,
                            CsStringType = To
                        };
                        list.Add(model);
                    }
                    Dict.Add(key, list);
                }
            }
        }

        public static List<DbCsharpTypeEntity> SqlServerMap => Dict["SqlServerCSharp"];

        public static List<DbCsharpTypeEntity> MySqlMap => Dict["MySqlCSharp"];

        public static List<DbCsharpTypeEntity> PostgreSqlMap => Dict["PostgreSqlCSharp"];

        public static List<DbCsharpTypeEntity> OracleMap => Dict["OracleCSharp"];

        public static List<DbCsharpTypeEntity> SqLiteMap => Dict["SQLiteCSharp"];

    }
}
